package icu.qrcode.msg5g.chatbot.qrcodeicuSdk;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QrcodeicuPosterExecutor {
    private QrcodeicuSdk sdk;

    private String posterId;

    private String posterCloudStorageId;

    private Map<String, Object> paramObj = new HashMap<>();

    public QrcodeicuPosterExecutor(QrcodeicuSdk sdk, String posterId, String posterCloudStorageId) {
        this.sdk = sdk;
        this.posterId = posterId;
        this.posterCloudStorageId = posterCloudStorageId;
    }

    public QrcodeicuPosterExecutor addTextParam(String name, String value) {
        this.paramObj.put(name, value);
        return this;
    }

    public String render() {
        String accessToken = this.sdk.getAccessToken();
        if (accessToken == null) {
            return null;
        }

        String api = "?a=render&boolSegment=false&pid=" + posterId + "&pcid=" + posterCloudStorageId;

        String posterParamNew = Base64.encode(new Gson().toJson(this.paramObj));

        String strResult = HttpUtil.createPost(this.sdk.renderEndpoint + api)
                .header("Authorization", "Bearer " + accessToken)
                .body(posterParamNew)
                .execute()
                .body();
        try {
            RenderResult r = (new Gson()).fromJson(strResult, RenderResult.class);
            return r.content.get(0).url;
        } catch (Exception e) {
        }
        return null;
    }
}

class RenderItem {
    public String url;
}

class RenderResult {
    public List<RenderItem> content;
}